import { ref, reactive } from "vue";
import { logout, updatePassword } from "@/api/admin/manager";
import { showMessage, showModel } from "@/composables/utils";
import { useRouter } from "vue-router";
import { useStore } from "vuex";


export function useRepassword() {
    const formDrawerRef = ref(null);

    const formRef = ref(null);

    const router = useRouter();
    const store = useStore();
    // 修改密码
    const onSubmit = () => {
        formRef.value.validate((vaild) => {
            if (!vaild) {
                return false;
            }
            // 开始加载
            formDrawerRef.value.showLoading();
            updatePassword(form)
                .then((res) => {
                    showMessage("修改密码成功，请重新登录");

                    store.dispatch("logout");

                    // 跳转登录页
                    router.push("/login");
                })
                .finally(() => {
                    formDrawerRef.value.hideLoading();
                });
        });
    };

    // 验证规则
    const rules = {
        oldpassword: [
            { required: true, message: "旧密码不能为空", trigger: "blur" },
        ],

        password: [{ required: true, message: "新密码不能为空", trigger: "blur" }],
        repassword: [
            { required: true, message: "确认密码不能为空", trigger: "blur" },
        ],
    };
    // 表单数据
    const form = reactive({
        oldpassword: "",
        password: "",
        repassword: "",
    });

    const openRePassword = () => {
        formDrawerRef.value.open();
    };

    return {
        formDrawerRef,
        formRef,
        onSubmit,
        rules,
        form,
        openRePassword,
    };
}


export function useLogout() {
    const router = useRouter();
    const store = useStore();
    // 退出登录
    const getlogout = () => {
        showModel("是否确认要退出登录？").then(() => {
            logout().finally(() => {
                store.dispatch("logout");

                // 跳转登录页
                router.push("/login");
                showMessage("退出登录成功！");
            });
        });
    };

    return { getlogout }
}